package com.my.spvideo.controller;



import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONObject;
import com.my.spvideo.util.user.SessionKeys;
import com.my.spvideo.util.user.User;
import com.my.spvideo.dao.mysql.baidumv.ChannelMapper;
import com.my.spvideo.dao.mysql.baidumv.CompanyMapper;
import com.my.spvideo.service.ChanneViewComService;

@Controller
@RequestMapping("Statistics")
public class ChanneViewComController extends BasicController{
	@Autowired
	private ChannelMapper channelMapper;
	@Autowired
	ChanneViewComService channeViewComService;
	@Autowired
	CompanyMapper companyMapper;
	
	@RequestMapping("list")
	public void channeViewList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String time = df.format(date);
		request.setAttribute("startTime", time);
		request.setAttribute("endTime", time);
		User user = (User) request.getSession().getAttribute(SessionKeys.USER);
		List<Integer> companyIdList = user.getProperty().getCompanyIdList();
		List<String> list = channelMapper.selectChannelsByCompanyId(companyIdList);
//		String path = request.getContextPath();
//		path+="/tables.jsp";
		request.setAttribute("list", list); 
		request.getRequestDispatcher("/tables.jsp").forward(request, response);	
	}

	@RequestMapping("incomViewlistSelect")
	public void incomViewlistSelect(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		User user = (User) request.getSession().getAttribute(SessionKeys.USER);
		List<Integer> companyIdList = user.getProperty().getCompanyIdList();
		
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String channelId = request.getParameter("channelId");
		if(startTime==null || endTime==null){
			to404(request, response, "参数异常");
			return;
		}
		LocalDate today = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate endDate = LocalDate.parse(endTime, formatter);
		if(today.isEqual(endDate)&&(channelId==null||channelId.equals("-1"))){
			to404(request, response, "参数异常");
			return;
		}
		JSONObject json = channeViewComService.getChannelincomlist(startTime,endTime,channelId,companyIdList);
		writeJSON(response, json);
	}

}
